﻿using Infrastructure.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Infrastructure.Filter
{
    public class GlobalActionAttribute : Attribute, IActionFilter, IFilterMetadata
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ModelState.IsValid)
            {
                return;
            }

            ApiResult apiResult = new ApiResult
            {
                Code = 101
            };
            foreach (ModelStateEntry value in context.ModelState.Values)
            {
                foreach (ModelError error in value.Errors)
                {
                    if (error.ErrorMessage.Contains("JSON"))
                    {
                        return;
                    }

                    if (!string.IsNullOrEmpty(apiResult.Msg))
                    {
                        apiResult.Msg += " | ";
                    }

                    apiResult.Msg += error.ErrorMessage;
                }
            }

            context.Result = new JsonResult(apiResult);
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }
    }
}
